package com.yoomiito.app.utils.inputfilter;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 限制只能输入数字
 * 仅适用于手机号344格式显示
 */
public class TelNum334Filter implements InputFilter {
    Pattern mPattern;

    private static final int PHONE_INDEX_3 = 3;
    private static final int PHONE_INDEX_4 = 4;
    private static final int PHONE_INDEX_8 = 8;
    private static final int PHONE_INDEX_9 = 9;
    private int maxLength;

    public TelNum334Filter() {
        mPattern = Pattern.compile("([0-9])*");
    }

    /**
     * @param source 新输入的字符串
     * @param start  新输入的字符串起始下标，一般为0
     * @param end    新输入的字符串终点下标，一般为source长度-1
     * @param dest   输入之前文本框内容
     * @param dstart 原内容起始坐标，一般为0
     * @param dend   原内容终点坐标，一般为dest长度-1
     * @return 输入内容
     */
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String sourceText = source.toString();
        String destText = dest.toString();

        //如果新输入的字符串为空 return ""
        if (TextUtils.isEmpty(sourceText)) {
            return "";
        }

        if (destText.length() > maxLength) {
            return "";
        }
        //如果不匹配 return ""
        Matcher matcher = mPattern.matcher(source);
        if (!matcher.matches()) {
            return "";
        }

        if (destText.length() == PHONE_INDEX_3) {
            return " " + sourceText;
        }
        if (destText.length() == PHONE_INDEX_8) {
            return " " + sourceText;
        }
        return sourceText;
    }

    public TelNum334Filter setMaxLength(int maxLength) {
        this.maxLength = maxLength;
        return this;
    }
}
